<?php

namespace control;
class supplierErpClass extends adIndexClass
{
    private const page = 'supplierErp'; # 权限
    private const table = 'aa_supplier'; # 数据表
    private const tableMx = 'aa_supplier_list'; # 数据表
    private const title = '供应商';


    /*列表页-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "orderNo", "title" => "供应商编码"]) .
            text(['name' => "name", "title" => "供应商名称",]);
        return $this->homeFun($this->search($html));

    }

    /*列表页-查询条件*/
    public function detailHome()
    {
        $html =
            text(["name" => "name", "title" => "姓名"]) .
            text(['name' => "phone", "title" => "手机号"]) .
            hidden(['name' => "id", "value" => $this->get('id')]);
        return $this->search($html);
    }

    public function detailSearch(): bool|string
    {
        $like = [
            "phone" => $this->post('phone'),
            "name" => $this->post('name'),
        ];
        //全等查询数组
        $equal = array(
            'orderId' => $this->post('id'),
        );
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]);
        // 查询自己
        $page = $this->page(array("table" => self::tableMx, "where" => $where, "order" => "phone desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        //
        $tr[] = [$checkAll, "姓名", "手机号"];
        //获取记录
        $url = root . "control/adIndex.php?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => "编辑", "click" => "layer('" . self::page . "','detailEdit',{id:'$array[id]',orderId : '{$this->post('id')}'})"),
            );
            $tr[] = [$this->dominate($dominate), $array['name'], $array['phone']];
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','detailEdit',{orderId : '{$this->post('id')}'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'delDetail'})\">删除</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function homeSearch(): bool|string
    {
        $like = [
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('name'),
        ];
        $exportLike = [
            "b.orderNo" => $this->post('orderNo'),
            "b.name" => $this->post('name'),
        ];
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        //全等查询数组
        $exportEqual = array(
            'b.coid' => self::$coid,
        );
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]);
        $exportWhere = search(["like" => $exportLike, "=" => $exportEqual]);
        // 查询自己
        if (!$this->power(self::page, "see")) {
            $where .= " and createId = '" . self::$stid . "' ";
        }
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "orderNo desc"));
        $_SESSION[self::page]['where'] = $exportWhere;
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        //
        $tr[] = [$checkAll, "供应商编码", "供应商名称", "授权手机数量"];
        //获取记录
        $url = root . "control/adIndex.php?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'$array[id]'})"),
                'detail' => array("title" => "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $tr[] = [$this->dominate($dominate), $array['orderNo'], $array['name'], $array['num']];
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "import")) {
            $button .=
                importTemplateClass::importTemplateButton(self::page) .
                $this->upButton(array("title" => "导入", "fun" => "importData"));
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.php?cla=" . self::page . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;

        return json_encode($json, 320);
    }

    /**
     * 导出
     */

    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $where = $_SESSION[self::page]['where'] ?? "";
            $title = ['供应商编码', '供应商名称', '姓名', '手机号'];
            $result = self::sqlFind("select b.orderNo,b.name,a.name as detailName,a.phone from aa_supplier_list as a left join  aa_supplier as b on a.orderId = b.id where 1=1 $where");
            if (is_array($result)) {
                foreach ($result as $array) {
                    $data[] = [$array['orderNo'], $array['name'], $array['detailName'], $array['phone']];
                }
            }
            $text = $this->control['name'] . "导出了供应商";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "供应商.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ["供应商编码", "供应商名称", "姓名", "手机号"];
            $data[] = ['s001', '供应商名称', '姓名', '手机号'];
            $text = $this->control['name'] . "下载了产品数据导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '供应商导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/

    public function importData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $data = $this->importHead();
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);

                    $field = [
                        'orderNo' => $cell[0],
                        'name' => $cell[1],
                        'detailName' => $cell[2],
                        'phone' => $cell[3],
                    ];
                    $annotation = [
                        'orderNo' => '供应商编码',
                        'name' => '供应商名称',
                        'detailName' => '姓名',
                        'phone' => '手机号',
                    ];
                    $rules = [
                        'orderNo' => 'required',
                        'name' => 'required',
                        'detailName' => 'required',
                        'phone' => 'required|tel',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $text = "第【{$i}】行：";
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } else {
                        $rowInfo = query(self::table, " orderNo = '$cell[0]'");
                        if (empty($rowInfo["id"])) {
                            $id = self::getId();
                            $tableField = [
                                "id" => $id,
                                'coid' => self::$coid,
                                'orderNo' => $field['orderNo'],
                                'name' => $field['name'],
                                'num' => 1,
                                'createId' => self::$stid,
                                'updateTime' => $this->time,
                                'time' => $this->time
                            ];
                            self::insert(["table" => self::table, "field" => $tableField]);
                            $tableMxField = [
                                "id" => self::getId(),
                                'orderId' => $id,
                                'name' => $field['detailName'],
                                'phone' => $field['phone'],
                                'createId' => self::$stid,
                                'updateTime' => $this->time,
                                'time' => $this->time
                            ];
                            $warn = self::insert(["table" => self::tableMx, "field" => $tableMxField]);
                        } else {
                            $mxInfo = query(self::tableMx, " orderId = '$rowInfo[id]' and phone = '$field[phone]'");
                            if (empty($mxInfo['id'])) {
                                self::update(["table" => self::table, "field" => ['num' => $rowInfo['num'] + 1], "where" => " orderId = '$rowInfo[id]'"]);
                                $tableMxField = [
                                    "id" => self::getId(),
                                    'orderId' => $rowInfo['id'],
                                    'name' => $field['detailName'],
                                    'phone' => $field['phone'],
                                    'createId' => self::$stid,
                                    'updateTime' => $this->time,
                                    'time' => $this->time
                                ];
                                $warn = self::insert(["table" => self::tableMx, "field" => $tableMxField]);
                            } else {
                                $text .= $rowInfo['orderNo'] . "【{$rowInfo['name']}】中已存在此手机号";
                                continue;
                            }

                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= self::title . "【{$cell[0]}】导入成功<br>";
                        } else {
                            $text .= self::title . "【{$cell[0]}】导入失败：编辑失败<br>" . $warn;
                        }
                    }
                }
            }
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = "成功导入" . $x . "条数据，详情请查看日志！";
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}' ");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.php?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮

            }
            if ($this->power(self::page, "del")) {
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            //生成表单
            $data['html'] = $this->tableShow([
                "button" => [],
                '基础信息' => [
                    [
                        "供应商编码" => $info['orderNo'],
                        "供应商名称" => $info['name'],
                    ],
                ],
                '授权信息' => [
                    [
                        $this->detailHome()
                    ]
                ]
            ]);
            //生成页面
            $html = $this->tab($data);

        }
        //返回
        return $html;
    }

    /*基本资料-弹出层*/
    public function edit(): string
    {

        $id = $this->post('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "供应商名称：" => text(array("name" => "name", "class" => "width200", "value" => $info['name'])),
                ),
            ),
        ));
        //返回
        return $this->layer(array("title" => "新增", "height" => 200, "width" => 500, "html" => $html));
    }


    /*基本资料-弹出层*/
    public function detailEdit(): string
    {

        $id = $this->post('id') ?: suiji();
        $info = query(self::tableMx, " id = '" . $id . "' ");
        $title = "编辑联系人";
        if (empty($info['id'])) {
            $title = "新增联系人";
        }
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "姓名：" => text(array("name" => "name", "class" => "width200", "value" => $info['name'])),
                ),
                array(
                    "手机号：" => text(array("name" => "phone", "class" => "width200", "value" => $info['phone'])),
                ),
            ),
            "hidden" => hidden(['name' => 'orderId', "value" => $this->post('orderId')]) . hidden(['name' => 'id', "value" => $info['id']])
        ));
        //返回
        return $this->layer(array("title" => $title, "height" => 240, "width" => 500, "html" => $html));
    }


    /*异步处理*/
    public function detailEditEdit(): bool|string
    {
        $id = empty($this->post('id')) ? self::getId() : $this->post('id');
        $orderId = $this->post('orderId');
        $field = [
            'name' => $this->post('name'),
            'phone' => $this->post('phone'),
        ];
        $annotation = [
            'name' => '姓名',
            'phone' => '手机号',
        ];
        $rules = [
            'name' => 'required',
            'phone' => 'required|tel',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::tableMx, " id = '" . $id . "' ");
        $this->startTrans();
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (self::total(['table' => self::tableMx, 'where' => " and phone = '$field[phone]' and orderId = '$orderId' and id !='$id' "]) > 0) {
            $json['warn'] = "【手机号】已存在";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, [
                "id" => $id,
                'orderId' => $orderId,
                'createId' => self::$stid,
                'updateTime' => $this->time,
                'time' => $this->time
            ]);
            $json['warn'] = self::insert(["table" => self::tableMx, "field" => $field]);
            $orderInfo = query(self::table, " id = '" . $orderId . "' ");
            $json['warn'] = self::update(["table" => self::table, "field" => ['num' => (float)$orderInfo['num'] + 1], "where" => "id='$orderInfo[id]'"]);

        } else {
            $json['warn'] = self::update(["table" => self::tableMx, "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }

        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            $this->commitTrans();
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . "：" . $field['name'] . ",ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.php?cla=' . self::page . '&fun=detail&id=' . $orderId;
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /*异步处理*/
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?? self::getId();
        $field = [
            'name' => $this->post('name'),
        ];
        $annotation = [
            'name' => '供应商名称',
        ];
        $rules = [
            'name' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, [
                "id" => $id,
                'coid' => self::$coid,
                'orderNo' => self::generateNo([
                    'prefix' => 'S',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '" . self::$coid . "'",
                ]),
                'createId' => self::$stid,
                'updateTime' => $this->time,
                'time' => $this->time
            ]);
            $json['warn'] = self::insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = self::update(["table" => self::table, "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }

        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . "：" . $field['name'] . ",ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.php?cla=' . self::page . '&fun=home';
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = $append = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'delDetail':
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '是否确认删除所选数据?';
                $function = 'deleteDetail';
                $form = self::page . 'OperateForm, listForm,detailSearchForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '是否确认删除所选数据?';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.php?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'append' => $append,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                delete(array("table" => self::table, "where" => " id = '$id' "));
                delete(array("table" => self::tableMx , "where" => " orderId = '$id' "));

                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.php?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function deleteDetail(): bool|string
    {
        $array = $this->post('listId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $info = query(self::table, " id ='{$this->post('id')}'");
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            self::update(["table" => self::table, "field" => ["num" => (float)$info['num'] - $x], "where" => "id ='$info[id]'"]);
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.php?cla=" . $this->get('cla') . "&fun=detail&id=$info[id]";
        }
        return json_encode($json, 320);
    }


}
